package android.dj.lbscamera.utils;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Bitmap.Config;
import android.graphics.PorterDuff.Mode;

public class UseUtils {
	/**
	 * save integer data into sharedPreference
	 * 
	 * @param context
	 * @param name
	 * @param key
	 * @param value
	 */
	public static void setPreferenceIntData(Context context, String name,
			String key, int value) {
		SharedPreferences settings = context.getSharedPreferences(name,
				Context.MODE_PRIVATE);
		SharedPreferences.Editor editor = settings.edit();
		editor.putInt(key, value);
		editor.commit();
	}

	/**
	 * save boolean data into sharedPreference
	 * 
	 * @param context
	 * @param name
	 * @param key
	 * @param value
	 */
	public static void setPreferenceBooleanData(Context context, String name,
			String key, Boolean value) {
		SharedPreferences settings = context.getSharedPreferences(name,
				Context.MODE_PRIVATE);
		SharedPreferences.Editor editor = settings.edit();
		editor.putBoolean(key, value);
		editor.commit();
	}

	/**
	 * save string data into sharedPreference
	 * 
	 * @param context
	 * @param name
	 * @param key
	 * @param value
	 */
	public static void setPreferenceStringData(Context context, String name,
			String key, String value) {
		SharedPreferences settings = context.getSharedPreferences(name,
				Context.MODE_PRIVATE);
		SharedPreferences.Editor editor = settings.edit();
		editor.putString(key, value);
		editor.commit();
	}

	/**
	 * get Int data from sharedPreference
	 * 
	 * @param context
	 * @param name
	 * @param key
	 * @param defaultValue
	 * @return
	 */
	public static int getPreferenceData(Context context, String name,
			String key, int defaultValue) {
		SharedPreferences settings = context.getSharedPreferences(name,
				Context.MODE_PRIVATE);
		return settings.getInt(key, defaultValue);

	}

	/**
	 * get boolean data from sharedPreference
	 * 
	 * @param context
	 * @param name
	 * @param key
	 * @param defaultValue
	 * @return
	 */
	public static boolean getPreferenceData(Context context, String name,
			String key, boolean defaultValue) {
		SharedPreferences settings = context.getSharedPreferences(name,
				Context.MODE_PRIVATE);
		return settings.getBoolean(key, defaultValue);

	}

	/**
	 * get String data from sharedPreference
	 * 
	 * @param context
	 * @param name
	 * @param key
	 * @param defaultValue
	 * @return
	 */
	public static String getPreferenceData(Context context, String name,
			String key, String defaultValue) {
		SharedPreferences settings = context.getSharedPreferences(name,
				Context.MODE_PRIVATE);
		return settings.getString(key, defaultValue);

	}

	/**
	 * move the file to new destination
	 * 
	 * @param srcFile
	 * @param destPath
	 * @return
	 */
	public static boolean MoveFile(File srcFile, String destPath) {
		// Destination directory
		File dir = new File(destPath);

		// Move file to new directory
		boolean success = srcFile.renameTo(new File(dir, srcFile.getName()));

		return success;
	}

	/**
	 * see if the file is exist
	 * 
	 * @param path
	 * @return
	 */
	public static boolean isFileExist(String path) {
		if (path != null) {
			return new File(path).exists();
		} else {
			return false;
		}
	}

	/**
	 * convert byte[] to bitmap
	 * 
	 * @param bytes
	 * @param opts
	 * @return
	 */
	public static Bitmap getPicFromBytes(byte[] bytes,
			BitmapFactory.Options opts) {
		if (bytes != null)
			if (opts != null)
				return BitmapFactory.decodeByteArray(bytes, 0, bytes.length,
						opts);
			else
				return BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
		return null;
	}

	/**
	 * change the bitmap size
	 * 
	 * @param bitmap
	 * @return
	 */
	public static Bitmap setBitmapSize(Bitmap bitmap, int newWidth,
			int newHeight) {

		if (bitmap == null)
			return null;
		int width = bitmap.getWidth();
		int height = bitmap.getHeight();
		float scaleWidth = ((float) newWidth) / width;
		float scaleHeight = ((float) newHeight) / height;

		Matrix matrix = new Matrix();
		matrix.postScale(scaleWidth, scaleHeight);

		Bitmap newbitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height,
				matrix, true);
		bitmap.recycle();
		return newbitmap;
	}

	/**
	 * round bitmap
	 * 
	 * @param bitmap
	 * @param roundPx
	 * @return
	 */
	public static Bitmap getRoundedCornerBitmap(Bitmap bitmap, float roundPx) {

		if (bitmap == null)
			return null;
		Bitmap output = Bitmap.createBitmap(bitmap.getWidth(),
				bitmap.getHeight(), Config.ARGB_8888);
		Canvas canvas = new Canvas(output);

		final int color = 0xff424242;
		final Paint paint = new Paint();
		final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
		final RectF rectF = new RectF(rect);

		paint.setAntiAlias(true);
		canvas.drawARGB(0, 0, 0, 0);
		paint.setColor(color);
		canvas.drawRoundRect(rectF, roundPx, roundPx, paint);

		paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
		canvas.drawBitmap(bitmap, rect, rect, paint);

		return output;
	}

	public static Bitmap getRoundedCornerFrameBitmap(Bitmap bitmap,
			float roundPx) {

		if (bitmap == null)
			return null;

		Bitmap output = Bitmap.createBitmap(bitmap.getWidth(),
				bitmap.getHeight(), Config.ARGB_8888);
		Canvas canvas = new Canvas(output);

		final int color = 0xff424242;
		final Paint paint = new Paint();
		final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
		final RectF rectF = new RectF(rect);

		paint.setAntiAlias(true);
		canvas.drawARGB(0, 0, 0, 0);
		paint.setColor(color);
		canvas.drawRoundRect(rectF, roundPx, roundPx, paint);

		paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
		canvas.drawBitmap(bitmap, rect, rect, paint);

		Rect rectL = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
		RectF rectFL = new RectF(rectL);

		Path path = new Path();
		path.addRoundRect(rectFL, roundPx, roundPx,
				android.graphics.Path.Direction.CCW);

		rectL = new Rect(1, 1, bitmap.getWidth() - 1, bitmap.getHeight() - 1);
		rectFL = new RectF(rectL);
		path.addRoundRect(rectFL, roundPx - 1, roundPx - 1,
				android.graphics.Path.Direction.CCW);
		path.setFillType(Path.FillType.EVEN_ODD);

		final Paint paintL = new Paint();
		paint.setColor(Color.BLACK);

		canvas.drawPath(path, paintL);

		return output;
	}

	/**
	 * read image
	 * 
	 * @param inStream
	 * @return
	 * @throws Exception
	 */
	public static byte[] readStream(InputStream inStream) throws Exception {
		byte[] buffer = new byte[1024];
		int len = -1;
		ByteArrayOutputStream outStream = new ByteArrayOutputStream();
		while ((len = inStream.read(buffer)) != -1) {
			outStream.write(buffer, 0, len);
		}
		byte[] data = outStream.toByteArray();
		outStream.close();
		inStream.close();
		return data;

	}

	/**
	 * get current time and return by default format or you appoint
	 * 
	 * @param format
	 * @return
	 */
	public static String getNow(String format) {
		if (null == format || "".equals(format)) {
			format = "yyyy-MM-dd HH:mm:ss";
		}
		SimpleDateFormat sdf = new SimpleDateFormat(format);
		String date = sdf.format(new Date());
		return date;
	}

	/**
	 * convert the date from String to Date
	 * 
	 * @param _date
	 *            the date you want to convert
	 * @param format
	 *            the DateFormat that matching the _date
	 * @return
	 */
	public static Date stringToDate(String _date, String format) {
		if (null == format || "".equals(format)) {
			format = "yyyy-MM-dd HH:mm:ss";
		}
		SimpleDateFormat sdf = new SimpleDateFormat(format);
		Date date = null;
		try {
			date = sdf.parse(_date);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return date;
	}

	/*
	 * To convert the InputStream to String we use the BufferedReader.readLine()
	 * method. We iterate until the BufferedReader return null which means
	 * there's no more data to read. Each line will appended to a StringBuilder
	 * and returned as String.
	 */
	public static String convertStreamToString(InputStream is) {
		BufferedReader reader = new BufferedReader(new InputStreamReader(is));
		StringBuilder sb = new StringBuilder();

		String line = null;
		try {
			while ((line = reader.readLine()) != null) {
				sb.append(line + "\n");
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				is.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		return sb.toString();
	}

	public static boolean isEmail(String email_string) {

		String check = "^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
		Pattern pattern = Pattern.compile(check);
		Matcher matcher = pattern.matcher(email_string);

		return matcher.matches();
	}

	/**
	 * MD5
	 * 
	 * @param val
	 * @return
	 * @throws NoSuchAlgorithmException
	 */
	public static String getMD5(String val) throws NoSuchAlgorithmException {
		MessageDigest md5 = MessageDigest.getInstance("MD5");
		md5.update(val.getBytes());
		byte[] m = md5.digest();
		String str = getString(m);
		// str = str.toUpperCase();
		return str;
	}

	private static String getString(byte[] b) {
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < b.length; i++) {

			int val = ((int) b[i]) & 0xff;
			if (val < 16) {
				sb.append("0");
			}
			sb.append(Integer.toHexString(val));
		}
		return sb.toString();
	}

	/**
	 * get bitmap by url
	 * 
	 * @param url
	 * @return
	 */
	public static Bitmap loadImageFromUrl(String url) {
		URL m;
		InputStream i = null;
		Bitmap d = null;
		try {
			m = new URL(url);
			i = (InputStream) m.getContent();
			d = BitmapFactory.decodeStream(i);
		} catch (Exception e1) {
			e1.printStackTrace();
		} catch (OutOfMemoryError e) {
			System.gc();
		}

		return d;
	}

	public static File convertBitmapToFile(File file, Bitmap bitmap) {
		try {
			FileOutputStream out = new FileOutputStream(file);
			if (bitmap.compress(Bitmap.CompressFormat.PNG, 0, out)) {
				out.flush();
				out.close();
			}
		} catch (Exception e) {

			e.printStackTrace();
		}
		return file;
	}
}
